package tcp

import (
	"bufio"
	"context"
	"fmt"
	"io"
	"net"
	"sync"
	"sync/atomic"
)

type EchoClient struct {
	Conn net.Conn
	wait sync.WaitGroup
}

func (e *EchoClient) Close() error {
	fmt.Println("CloseCloseCloseCloseClose")
	e.wait.Wait()
	e.Conn.Close()
	return nil
}

type EchoHandler struct {
	activeConn sync.Map
	closing    atomic.Bool
}

func MakeHandler() *EchoHandler {
	return &EchoHandler{}
}
func (e *EchoHandler) Handle(ctx context.Context, conn net.Conn) {
	if e.closing.Load() {
		conn.Close()
	}
	client := &EchoClient{Conn: conn}
	e.activeConn.Store(client, struct {
	}{})
	reader := bufio.NewReader(conn)
	for true {
		readString, err := reader.ReadString('\n')
		if err != nil {
			if err == io.EOF {
				fmt.Println("EEEEEEEE")
				e.activeConn.Delete(client)
			} else {
				fmt.Println("wwwwwwwwww")
			}
			return
		}
		client.wait.Add(1)
		b := []byte(readString)
		conn.Write(b)
		client.wait.Done()
	}
}
func (e *EchoHandler) Close() error {
	e.closing.Store(true)
	e.activeConn.Range(func(key, value any) bool {
		c := key.(*EchoClient)
		c.Conn.Close()
		return true
	})
	return nil
}
